//
//  MessageViewController.m
//  ZPIOSEducation
//
//  Created by 董伟1 on 17/1/18.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "MessageViewController.h"
#import "MessageCell.h"
#import "MessageNextViewController.h"

@interface MessageViewController () <UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray  *dataArray;
}

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"消息";
    
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    dataArray = [[NSMutableArray  alloc] init];
    [self  requestMessageData];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter  defaultCenter] postNotificationName:@"checkExistUnReadMessage" object:nil];
}

#pragma mark - 网络请求
#pragma mark 获取消息列表数据
- (void)requestMessageData
{
    [self  showHudithString:@"加载中..."];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"stuId"],@"id", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIHome@"home/getMessage.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            [dataArray  removeAllObjects];
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"message"] isKindOfClass:[NSArray  class]]) {
                [dataArray  addObjectsFromArray:[[responseObject  objectForKey:@"result"] objectForKey:@"message"]];
            }
            [self.mainTableView  reloadData];
            
            if (dataArray.count == 0) {
                [self  showNoDataViewWithTitle:@"还没有消息哦~"];
            }else {
                [self  hiddenNoDataView];
            }
            
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

#pragma mark 将消息更新为已读
- (void)sendUpdateMessageRequestWithIndex:(NSInteger)index
{
    NSDictionary  *tempDic = [dataArray  objectAtIndex:index];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"stuId"],@"id",[tempDic  objectForKey:@"type"],@"type", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIHome@"home/updateMessage.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                [self  requestMessageData];
            }
            
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray  count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 74.;
}

- (UITableViewCell  *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MessageCell";
    MessageCell  *cell = (MessageCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MessageCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSInteger  row = [indexPath  row];
    NSDictionary  *tempDic = [dataArray  objectAtIndex:row];
    
    NSInteger  type = [[tempDic  objectForKey:@"type"] integerValue];
    switch (type) {
        case 1:
            cell.typeImv.image = [UIImage  imageNamed:@"Message_Type1"];
            cell.titleLab.text = @"作业提醒";
            break;
        case 2:
            cell.typeImv.image = [UIImage  imageNamed:@"Message_Type2"];
            cell.titleLab.text = @"问答提醒";
            break;
        case 3:
            cell.typeImv.image = [UIImage  imageNamed:@"Message_Type3"];
            cell.titleLab.text = @"系统通知";
            break;
        case 4:
            cell.typeImv.image = [UIImage  imageNamed:@"Message_Type4"];
            cell.titleLab.text = @"课堂评价";
            break;
        case 5:
            cell.typeImv.image = [UIImage  imageNamed:@"Message_Type5"];
            cell.titleLab.text = @"社区提醒";
            break;
            
        default:
            cell.typeImv.image = nil;
            cell.titleLab.text = @"";
            break;
    }
    
    cell.timeLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"timeString"]];
    cell.detailLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"content"]];
    
    NSString  *unread = [tempDic  objectForKey:@"unread"];
    if (unread && ![unread  isEqual:[NSNull  null]]) {
        NSInteger  unreadInter = [unread  integerValue];
        if (unreadInter > 0) {
            cell.numLab.hidden = NO;
            NSString  *numStr = [NSString  stringWithFormat:@"%@",unread];
            if (unreadInter > 99) {
                numStr = @"99+";
            }
            CGFloat labelWidth = [numStr sizeWithFont:[UIFont  systemFontOfSize:11.]].width;
            cell.labelWidth.constant = labelWidth + 16;
            cell.numLab.text = numStr;
        }else {
            cell.numLab.hidden = YES;
        }
    }else {
        cell.numLab.hidden = YES;
    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  row = [indexPath  row];
    NSDictionary  *tempDic = [dataArray  objectAtIndex:row];
    MessageNextViewController  *viewController = [[MessageNextViewController  alloc] initWithNibName:@"MessageNextViewController" bundle:nil];
    NSString  *titleStr = @"";
    NSInteger  type = [[tempDic  objectForKey:@"type"] integerValue];
    switch (type) {
        case 1:
            titleStr = @"作业提醒";
            break;
        case 2:
            titleStr = @"问答提醒";
            break;
        case 3:
            titleStr = @"系统通知";
            break;
        case 4:
            titleStr = @"课堂评价";
            break;
        case 5:
            titleStr = @"社区提醒";
            break;
            
        default:
            
            break;
    }
    viewController.titleStr = titleStr;
    viewController.typeStr = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"type"]];
    [self.navigationController  pushViewController:viewController animated:YES];
    
    NSString  *unread = [tempDic  objectForKey:@"unread"];
    if (unread && ![unread  isEqual:[NSNull  null]] && [unread integerValue] > 0) {
        [self  sendUpdateMessageRequestWithIndex:row];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
